package com.backend.system.service.processors.menu;

import com.backend.system.beans.menu.MenuDisableOrEnableReq;
import com.backend.system.common.CustomException;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.Menu;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 菜单禁用或启用处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.MENU_DISABLE_OR_ENABLE)
public class MenuDisableOrEnableProcessor extends AbstractProcessorTemplate<MenuDisableOrEnableReq, Boolean> {

    private Boolean enable;

    private Menu menu;

    @Override
    protected void init(ProcessorContext<MenuDisableOrEnableReq> context) {
        MenuDisableOrEnableReq req = context.getData();
        menu = null;
        enable = Objects.equals(1, req.getEnabled());

        // 查询菜单
        Long menuId = req.getMenuId();
        Menu menu = menuService.getById(menuId);
        if (menu == null) {
            throw CustomException.argsError("菜单不存在");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<MenuDisableOrEnableReq> context) {
        LambdaUpdateWrapper<Menu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Menu::getEnabled, enable ? 1 : 0);
        updateWrapper.eq(Menu::getId, menu.getId());
        updateWrapper.or(m -> m.eq(Menu::getParentId, menu.getId()));
        return menuService.update(updateWrapper);
    }
}
